<template>
  <div class="chat-container">
    <!-- 消息展示区域 -->
    <div class="message-area">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.role]"
      >
        <!-- 使用Markdown渲染容器 -->
        <div
            v-if="msg.role === 'assistant'"
            class="markdown-content"
            v-html="safeRenderMarkdown(msg.content)"
        ></div>
        <template v-else>
          {{ msg.content }}
        </template>
      </div>
      <div v-if="isLoading" class="loading">AI正在思考中...</div>
    </div>

    <!-- 输入控制区域 -->
    <div class="input-area">
      <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="输入你的问题..."
      />
      <button @click="sendMessage" :disabled="isLoading">
        {{ isLoading ? '生成中...' : '发送' }}
      </button>
    </div>
    <div v-if="isLoading" class="loading">
      <span class="loading-dot">.</span>
      <span class="loading-dot">.</span>
      <span class="loading-dot">.</span>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import {marked} from 'marked';
import hljs from 'highlight.js';
import DOMPurify from 'dompurify';
import axios from "axios";

const inputMessage = ref('');
const messages = ref([]);
const isLoading = ref(false);

// 配置marked
marked.setOptions({
  gfm: true,          // 启用GitHub风格Markdown
  breaks: true,       // 自动换行
  headerIds: true,    // 生成标题ID
  highlight: (code, lang) => {
    return hljs.highlightAuto(code).value;
  },
  pedantic: false,    // 不严格遵循Markdown规范
  sanitize: false,    // 不自动净化HTML输出，因为我们使用DOMPurify
});

// 安全渲染方法
const safeRenderMarkdown = (content) => {
  const rawHtml = marked(content);
  return DOMPurify.sanitize(rawHtml, {
    ALLOWED_TAGS: [
      'h1', 'h2', 'h3', 'h4', 'h5', 'h6', // 添加标题标签
      'p', 'br', 'code', 'pre', 'strong', 'em',
      'a', 'ul', 'ol', 'li', 'blockquote', 'hr'
    ]
  });
};

// AI内容格式化方法
const formatAssistantText = (text) => {
  return text
      .replace(/</g, '&lt;')  // 防止XSS攻击
      .replace(/>/g, '&gt;')
      .replace(/\n/g, '<br>')
      .replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>');
};

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;

  try {
    messages.value.push({
      role: 'user',
      content: inputMessage.value
    });

    messages.value.push({
      role: 'assistant',
      content: ''
    });
    const assistantMsgIndex = messages.value.length - 1;

    isLoading.value = true;
    const userMessage = inputMessage.value;
    inputMessage.value = '';

    // eventSource = new EventSource(`http://localhost:8084/ai?userInput=${encodeURIComponent(userMessage)}`);
    // eventSource = new EventSource(`http://localhost:8084/ai?userInput=${userMessage}`);
    const response = await axios.get('http://47.111.128.196:8084/ai', {
      params: {userInput: userMessage}
    });

    if (response.data?.output?.choices?.[0]?.message?.content) {
      messages.value[assistantMsgIndex].content =
          response.data.output.choices[0].message.content;
    } else {
      messages.value[assistantMsgIndex].content = '未能获取有效回复';
    }

  } catch (error) {
    console.error('请求失败:', error);
    messages.value[assistantMsgIndex].content = '请求失败，请重试';
  } finally {
    isLoading.value = false;
  }
};


</script>

<style scoped>
.loading-dot {
  animation: dot-pulse 1.4s infinite;
}

@keyframes dot-pulse {
  0%, 20% { opacity: 0.2; }
  50% { opacity: 1; }
  80%, 100% { opacity: 0.2; }
}

/* Markdown标题样式 */
.markdown-content h1 {
  font-size: 2em;
  margin: 0.67em 0;
  border-bottom: 2px solid #eee;
  padding-bottom: 0.3em;
}

.markdown-content h2 {
  font-size: 1.5em;
  margin: 0.83em 0;
  color: #333;
}

.markdown-content h3 {
  font-size: 1.17em;
  margin: 1em 0;
  color: #444;
}

/* Markdown基础样式 */
.markdown-content {
  line-height: 1.6;
  text-align: left;
}

.markdown-content pre {
  background: #f8f8f8;
  padding: 1em;
  border-radius: 8px;
  overflow-x: auto;
  margin: 1em 0;
}

.markdown-content code {
  font-family: 'Fira Code', monospace;
  font-size: 14px;
}

.markdown-content blockquote {
  border-left: 4px solid #ddd;
  padding-left: 1em;
  color: #666;
  margin: 1em 0;
}

/* 新增代码块样式 */
pre {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 8px;
  margin: 10px 0;
  overflow-x: auto;
}

code {
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
}

.message.assistant {
  line-height: 1.6;
}

.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.message-area {
  height: 80vh;
  overflow-y: auto;
  border: 1px solid #ddd;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
}

.message {
  margin: 10px 0;
  padding: 10px 15px;
  border-radius: 15px;
  max-width: 70%;
}

.user {
  background-color: #e3f2fd;
  margin-left: auto;
}

.assistant {
  background-color: #f5f5f5;
  margin-right: auto;
}

.input-area {
  display: flex;
  gap: 10px;
}

input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.stop-btn {
  background-color: #ff4444;
}

.loading {
  color: #666;
  font-style: italic;
}
</style>
